package com.signway.harmony_demo.devices;

import com.signway.harmony_demo.ResourceTable;
import com.signway.harmony_demo.utils.CommonData;
import com.signway.harmony_demo.utils.LogUtil;
import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.distributedschedule.interwork.DeviceInfo;

import java.util.List;

public class SelectDeviceDialog {
    public static final String TAG = CommonData.TAG + SelectDeviceDialog.class.getSimpleName();
    private static final int DIALOG_WIDTH = 840;

    private static final int DIALOG_HEIGHT = 900;

    private CommonDialog commonDialog;

    public SelectDeviceDialog(Context context, List<DeviceInfo> devices, Listener listener) {
        LogUtil.info(TAG, "SelectDeviceDialog......");
        initView(context, devices, listener);
    }

    private void initView(Context context, List<DeviceInfo> devices, Listener listener) {
        commonDialog = new CommonDialog(context);
        commonDialog.setAlignment(LayoutAlignment.CENTER);
        commonDialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
        commonDialog.setAutoClosable(true);
        Component dialogLayout = LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_dialog_select_devices, null, false);
        commonDialog.setContentCustomComponent(dialogLayout);

        ListContainer devicesListContainer = (ListContainer)dialogLayout
                .findComponentById(ResourceTable.Id_list_devices);
        DevicesListAdapter devicesListAdapter = new DevicesListAdapter(context, devices);
        devicesListContainer.setItemProvider(devicesListAdapter);
        devicesListContainer.setItemClickedListener((listContainer, component, position, id) -> {
            listener.onItemClickedListener(devices.get(position));
            commonDialog.hide();
        });

        dialogLayout.findComponentById(ResourceTable.Id_cancel).setClickedListener(component -> {
            commonDialog.hide();
            listener.onHideListener();
        });
    }

    public void show() {
        commonDialog.show();
    }

    public interface Listener {
        void onItemClickedListener(DeviceInfo deviceInfo);
        void onHideListener();
    }
}
